package com.im.service.job;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.im.service.domain.dto.OrgUserDTO;
import com.im.service.domain.entity.ImOrg;
import com.im.service.domain.entity.ImUser;
import com.im.service.service.ImOrgService;
import com.im.service.service.ImUserService;
import com.im.service.service.RongHuiService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @author liuzhiqiang
 */
@Component
public class SyncOrgUserJob {

    @Autowired
    private RongHuiService rongHuiService;
    @Autowired
    private ImOrgService orgService;
    @Autowired
    private ImUserService imUserService;

    @Value("${avatarUrl}")
    private String avatarUrl;

    @Scheduled(cron = "0 0 23 * * ?")
    public void syncOrgUser() {
        orgService.remove(Wrappers.query());
        List<ImOrg> orgList = rongHuiService.orgList();
        orgService.saveBatch(orgList);
        // 处理父级关系
        for (ImOrg imOrg : orgList) {
            ImOrg parentOrg = orgList.stream().filter(org -> StrUtil.equals(org.getRemoteOrgId(), imOrg.getRemoteOrgParentId())).findAny().orElse(null);
            if (ObjUtil.isNotNull(parentOrg)) {
                imOrg.setParentId(parentOrg.getId());
            }
        }
        orgService.saveOrUpdateBatch(orgList);

        List<OrgUserDTO> userList = rongHuiService.userList();

        for (OrgUserDTO orgUserDTO : userList) {
            ImOrg userOrg = orgList.stream().filter(org -> StrUtil.equals(org.getRemoteOrgId(), orgUserDTO.getDepartmentId())).findAny().orElse(null);
            ImUser imUser = imUserService.getOne(
                    Wrappers.lambdaQuery(ImUser.class)
                            .eq(ImUser::getRemoteUserId, orgUserDTO.getRemoteUserId())
                            .last("limit 1")
            );
            if (ObjUtil.isNull(imUser)) {
                imUser = BeanUtil.toBean(orgUserDTO, ImUser.class);
                if (ObjUtil.isNotNull(userOrg)) {
                    imUser.setOrgId(userOrg.getId());
                }
                imUser.setAvatar(avatarUrl + "user.png");
                imUserService.register(imUser);
            } else {
                if (ObjUtil.isNotNull(userOrg)) {
                    imUser.setOrgId(userOrg.getId());
                } else {
                    imUser.setOrgId(0L);
                }
                imUser.setUsername(orgUserDTO.getUsername());
                imUser.setSignature(orgUserDTO.getSignature());
                imUser.setNickname(orgUserDTO.getNickname());
                imUser.setAvatar(avatarUrl + "user.png");
                imUserService.updateById(imUser);
            }
        }
    }
}
